<template>
  <div class="address-container">
    <!-- @click-item="clickAddress" -->
    <van-address-list :list="addressList" :switchable="false" @add="onAdd" @edit="onEdit">
      <template #item-bottom="addressInfo">
        <div class="item-bottom">
          <div class="default-address" v-if="addressInfo.isDefault">
            <van-checkbox checked-color="#ee0a24" :value="true" />
            <span>已设默认</span>
          </div>
          <!-- 占位 -->
          <div v-else></div>
          <!-- 注意：从购物车页面来有此按钮，其他地方过来就没有 -->
          <van-button
            plain
            type="primary"
            size="small"
            v-if="$store.state.isShowUseAddressButton"
            @click="clickAddress(addressInfo)"
            >使用此地址</van-button
          >
        </div>
      </template>

      <template #tag="{ province, city, county }">
        {{ province + city + county }}
      </template>
    </van-address-list>

    <van-empty v-if="addressList.length === 0" description="暂无地址" />
  </div>
</template>

<script>
import { reqUserAddressList } from '@/api/user'
export default {
  data() {
    return {
      addressList: [],
      isEdit: false, // 记录是否处于编辑状态
    }
  },
  methods: {
    clickAddress(addressInfo) {
      // 若处于编辑状态，不执行单击事件（阻止下面编辑事件向上传播）
      if (this.isEdit) {
        return
      }

      // 将当前单击的地址信息存入到vuex中
      this.$store.commit('setSelectAddressInfo', addressInfo)
      // 返回上一个页面
      this.$router.back()
    },
    onEdit(addressInfo) {
      this.isEdit = true // 处于编辑状态
      console.log('edit')
      this.$router.push('/editaddress/' + addressInfo.id)
    },
    onAdd() {
      this.$router.push('/addressadd')
    },
    async getUserAddressList() {
      let addressList = await reqUserAddressList()
      this.addressList = addressList
    },
  },
  beforeRouteEnter(to, from, next) {
    // console.log('addressList beforeRouteEnter')
    next((vc) => {
      // vc:当前组件实例对象
      if (from.path === '/shopcar') {
        vc.$store.commit('setUseAddressButton', true)
      }

      if (from.path === '/user') {
        vc.$store.commit('setUseAddressButton', false)
      }
    })
  },
  mounted() {
    this.getUserAddressList()
  },
}
</script>

<style lang="scss" scoped>
.address-container {
  .van-address-list {
    padding: 0;

    .van-address-item {
      border-radius: 0;
    }

    .item-bottom {
      display: flex;
      justify-content: space-between;

      .default-address {
        display: flex;
        align-items: center;
        margin-top: 4px;
        font-size: 14px;
        color: #d92929;

        span {
          margin-left: 4px;
        }
      }
    }
  }
}
</style>
